const { LinValidator, Rule } = require('@root/core/lin-validator')
const { User } = require('@models/user')

class RegisterValidator extends LinValidator {
  constructor() {
    super()
    this.username = [
      new Rule('isLength', '用户名最少4个字符，最多32个字符', {
        min: 4,
        max: 32
      })
    ]
    this.password1 = [
      new Rule('isLength', '密码至少6个字符，最多32个字符', {
        min: 6,
        max: 32
      }),
      new Rule('matches', '密码不符合规范', '^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]')
    ]
    this.password2 = this.password1
    this.nickname = [
      new Rule('isLength', '昵称最少4个字符，最多32个字符', {
        min: 4,
        max: 32
      }),
    ]
  }

  /**
   * 注册时两次密码验证
   * @param {*} vals 请求传递的所有参数==ctx
   */
  validatePassword(vals) {
    const psw1 = vals.body.password1
    const psw2 = vals.body.password2
    if (psw1 !== psw2) {
      throw new Error('两个密码必须相同')
    }
  }

  /**
   * 用户名验证
   * @param {*} vals 请求传递的所有参数==ctx
   */
  async validateUserName(vals) {
    const username = vals.body.username
    const user = await User.findOne({
      where: {
        username
      }
    })

    if(user) {
      throw new Error('用户名已存在')
    }
  }

  /**
   * 昵称验证
   * @param {*} vals 请求传递的所有参数==ctx
   */
  async validateNickName(vals) {
    const nickname = vals.body.nickname
    const user = await User.findOne({
      where: {
        nickname
      }
    })

    if (user) {
      throw new Error('昵称已存在')
    }
  }
}

class LoginValidator extends LinValidator {
  constructor() {
    super()
    this.username = [
      new Rule('isLength', '用户名最少4个字符，最多32个字符', {
        min: 4,
        max: 32
      })
    ]
    this.password = [
      new Rule('isLength', '密码至少6个字符，最多32个字符', {
        min: 6,
        max: 32
      }),
      new Rule('matches', '密码不符合规范', '^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]')
    ]
  }
}

class PositiveIntegerValidator extends LinValidator {
  constructor() {
    super()
    this.id = [
      new Rule('isInt', '需要是正整数', {
        min: 1
      }),
    ]
  }
}

class AddContentValidator extends LinValidator {
  constructor() {
    super()
    this.content = [
      new Rule('isLength', '内容不能为空', {
        min: 1
      })
    ]
    this.title = [
      new Rule('isLength', '内容不能为空', {
        min: 1
      })
    ]
  }
}

class UpdateContentValidator extends PositiveIntegerValidator {
  constructor() {
    super()
    this.content = [
      new Rule('isLength', '内容不能为空', {
        min: 1
      })
    ]
    this.title = [
      new Rule('isLength', '内容不能为空', {
        min: 1
      })
    ]
  }
}

module.exports = {
  RegisterValidator,
  LoginValidator,
  PositiveIntegerValidator,
  UpdateContentValidator,
  AddContentValidator
}
